<template>
	<view class="location-components text-cut-1" :style="[wrapStyle,positioTextStylee]">
		<u-icon name="map" :size="fontSize" :color="color"></u-icon>
		<text class="position-text">{{ defaultAddress.name || addressInfo.name || '获取地址' }}</text>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import mixins from '@/mixins/components.js';
export default {
	name: 'location',
	mixins: [mixins],
	props: {
		color: {
			type: String,
			default: '#fff'
		},
		fontSize: {
			type: String,
			default: '24'
		},
		defaultAddress: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			addressInfo: {
				name: '',
				areaCode: '',
			}, // 地址信息
			currentUrl: '',
			env: '',
			urls: {}, // 地址列表
		};
	},
	computed: {
		positioTextStylee() {
			const { color,fontSize } = this;
			return {
				'color': color,
				'font-size': /[rpx]/.test(fontSize) ? fontSize : `${fontSize}rpx`
			};
		},
	},
	created() {
		this.handleGetPosition();
	},
	methods: {
		// 获取位置信息
		handleGetPosition() {
			let isEmpty = this.$u.test.empty(this.defaultAddress);
			if(isEmpty){
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					success: position => {
						uni.request({
							url: `https://restapi.amap.com/v3/geocode/regeo`,
							method: 'GET',
							data: {
								key: this.mapKey,
								location: `${position.longitude},${position.latitude}`,
								// extensions: extensions ? 'all' : 'base'
							},
							success: (res) => {
								let address = res.data.regeocode.addressComponent;
								this.addressInfo.areaCode = address.adcode;
								this.addressInfo.name = `${address.city} ${address.district}`
								this.addressInfo.longitude = address.streetNumber.location.split(',')[0];
								this.addressInfo.latitude = address.streetNumber.location.split(',')[1];
								this.$emit('on-success',this.addressInfo)
							}
						});
					},
					fail: err => {
						console.log(err);
						this.$emit('on-error',err)
						if(err.errMsg == 'getLocation:fail auth deny'){
							this.$toast('您拒绝了授权获取位置信息,如需获取请手动开启获取位置权限')
						}
					}
				});
			}else {
				this.$emit('on-success',this.defaultAddress)
			}
		},
	},
};
</script>

<style scoped lang="scss">
.location-components {
	flex-shrink: 0;
	.position-text{
		margin-left: 8rpx;
	}
}
</style>
